package com.ys.service.business.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.ys.enume.base.TransactionTypeEnum;
import com.ys.service.sys.CommonApiService;
import com.ys.util.RedisUtil;
import com.ys.vo.W;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.amazonorder.TbBaseinfoDwmc;
import com.ys.entity.amazonorder.TbBaseinfoSpcz;
import com.ys.entity.amazonorder.TbBaseinfoSppl;
import com.ys.entity.amazonorder.TbBaseinfoSppm;
import com.ys.entity.amazonorder.TbBaseinfoSpyt;
import com.ys.entity.base.TbSite;
import com.ys.entity.business.TpBoutique;
import com.ys.entity.business.TpBoutiqueSiteDetail;
import com.ys.entity.business.TpCodeNo;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.business.TpProductActiveComponent;
import com.ys.entity.business.TpProductBasis;
import com.ys.entity.business.TpProductBasisComponent;
import com.ys.entity.business.TpProductBq;
import com.ys.entity.business.TpProductBqSp;
import com.ys.entity.business.TpProductBqSpZj;
import com.ys.entity.business.TpProductMaterial;
import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.purchase.TcgDistribution;
import com.ys.entity.purchase.TcgDistributionSon;
import com.ys.entity.storage.TccAssemblyMaintain;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsMenuNo;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.business.TpProductBqEnum;
import com.ys.enume.business.TpProductMaterialEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.business.BusinessMapper;
import com.ys.mapper.business.TpBoutiqueMapper;
import com.ys.mapper.business.TpBoutiqueSiteDetailMapper;
import com.ys.mapper.business.TpCodeNoMapper;
import com.ys.mapper.business.TpProductActiveComponentMapper;
import com.ys.mapper.business.TpProductActiveMapper;
import com.ys.mapper.business.TpProductBasisComponentMapper;
import com.ys.mapper.business.TpProductBasisMapper;
import com.ys.mapper.business.TpProductBqMapper;
import com.ys.mapper.business.TpProductBqSpMapper;
import com.ys.mapper.business.TpProductBqSpZjMapper;
import com.ys.mapper.business.TpProductMaterialMapper;
import com.ys.mapper.finance.TcwAccountCountForCompanyMapper;
import com.ys.mapper.purchase.TcgDistributionMapper;
import com.ys.mapper.purchase.TcgDistributionSonMapper;
import com.ys.mapper.storage.TccAssemblyMaintainMapper;
import com.ys.mapper.sys.YsMenuNoMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.business.TpProductBqService;
import com.ys.service.flow.YspTaskService;
import com.ys.util.CheckUtil;
import com.ys.util.DateUtil;
import com.ys.util.RandomUtil;
import com.ys.util.shiro.BeanUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;

import cn.hutool.core.bean.BeanUtil;


/**
 * 商品备案申请
 */
@Service("TpProductBqService")
public class TpProductBqServiceImpl implements TpProductBqService {
	private static final Logger logger = LoggerFactory.getLogger(TpProductBqServiceImpl.class);

	@Autowired
	private TpProductBqMapper tpProductBqMapper;

	@Autowired
	private TpProductBqSpMapper tpProductBqSpMapper;

	public static Long MENU_ID = 10183L;

	public static Long MENU_ID_BP = 10169L;

	@Resource
	private YsMenuNoMapper ysMenuNoMapper;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private TpProductBqSpZjMapper tpProductBqSpZjMapper;

	@Autowired
	private TpProductBasisMapper tpProductBasisMapper;

	@Autowired
	private TpProductActiveMapper tpProductActiveMapper;

	@Autowired
	private TpProductBasisComponentMapper tpProductBasisComponentMapper;


	@Autowired
	private TpProductActiveComponentMapper tpProductActiveComponentMapper;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private TpBoutiqueMapper tpBoutiqueMapper;

	@Autowired
	private TpBoutiqueSiteDetailMapper tpBoutiqueSiteDetailMapper;

	@Autowired
	private TccAssemblyMaintainMapper tccAssemblyMaintainMapper;

	@Autowired
	private TpProductMaterialMapper tpProductMaterialMapper;

	@Autowired
	private BusinessMapper businessMapper;

	@Autowired
	private TcgDistributionMapper tcgDistributionMapper;

	@Autowired
	private TcgDistributionSonMapper tcgDistributionSonMapper;

	@Autowired
	private TpCodeNoMapper tpCodeNoMapper;

	@Autowired
	private TcwAccountCountForCompanyMapper tcwAccountCountForCompanyMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private RedisUtil redisUtil;


	@Autowired
	private CommonApiService<TpProductBq> commonApiService;





	/**
	 * 商品备案申请新增
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R add(Map<String, Object> params,String subData) throws Exception {
		// 验证订单号
		if (new TpProductBq().setBid(params.get("bid").toString()).count() > 0) {
			return R.error("该商品备案申请单号已存在");
		}
		// 验证是否有详情数据
		JSONArray detailJA = JSON.parseArray(subData);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();

		TpProductBq tpProductBq = new TpProductBq();
		tpProductBq.setBid(params.get("bid").toString());
		tpProductBq.setVgsBm(params.get("vgsBm").toString());
		tpProductBq.setCreateChangeId(String.valueOf(tsUserChange.getId()));
		tpProductBq.setEffectStock(FlowEnum.EffectStock.NOT_EFFECT.value);
		tpProductBq.setStatus(0);
		int isAddTpBoutique = tpProductBqMapper.insert(tpProductBq);
		String commodityProperty = "";
		if(isAddTpBoutique>0){
			// 添加新增商品明细
			for (int i = 0; i < detailJA.size(); i++) {
				JSONObject detailJO = detailJA.getJSONObject(i);
				TpProductBqSp tpProductBqSp = JSON.parseObject(JSON.toJSONString(detailJO), TpProductBqSp.class);
				tpProductBqSp.setPid(tpProductBq.getId());
				commodityProperty = detailJO.get("commodityProperty").toString();
				R yzcs = yzcs(tpProductBqSp);
				if (yzcs.getCode().equals(1)){
					return yzcs;
				}
				//查询商品编码
				try {
					R r = addSp(detailJO, tpProductBqSp, tpProductBq,false);
					if (r.getCode() == 1){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return R.error(r.getMsg());
					}
				} catch (Exception e) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("新增商品列表失败!");
				}
			}

		}else {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("新增商品备案申请失败!");
		}
		YsMenu ysMenu = new YsMenu().setId(MENU_ID_BP).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, tpProductBq.getBid(), createUserId);
		}
		return R.ok(AddDto.gotoEdit("/web/business/tpProductBq/toEdit?bid=" + tpProductBq.getBid()+"&commodityProperty=" +commodityProperty));
	}



	/**
	 * 修改
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R update(Map<String, Object> params,String subData) throws Exception {
		// 验证是否有详情数据
		JSONArray detailJA = JSON.parseArray(subData);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}

		TpProductBq tpProductBq = JSON.parseObject(JSON.toJSONString(params), TpProductBq.class);
		if (new TpProductBq().setId(tpProductBq.getId()).count() == 0){
			return R.error("保存失败,商品备案申请不存在!");
		}

		//判断是否实在制单中
		Integer flowState = yspTaskService.flowState(tpProductBq.getBid());

		if (flowState != 0){
			return R.error("商品备案申请单不是制单中,不允许保存!");
		}
		tpProductBq.setVgsBm(params.get("vgsBm").toString());
		tpProductBq.setUpdateTime(new Date());
		tpProductBqMapper.update(tpProductBq);
		String commodityProperty = "";
		TpProductBqSp  tpProductBqSp1 = null;
		Integer count = 0;
		// 修改新增商品明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			TpProductBqSp tpProductBqSp = JSON.parseObject(JSON.toJSONString(detailJO), TpProductBqSp.class);
			tpProductBqSp.setPid(tpProductBq.getId());
			commodityProperty = detailJO.get("commodityProperty").toString();
			R yzcs = yzcs(tpProductBqSp);
			if (yzcs.getCode().equals(1)){
				return yzcs;
			}

			//查询商品编码
			try {
				tpProductBqSp.setName(detailJO.get("name").toString());
				tpProductBqSp.setPriceService(new BigDecimal(detailJO.get("priceService").toString()));
				tpProductBqSp.setIsSuperior(detailJO.get("isSuperior").toString());
				tpProductBqSp.setVsfJp(detailJO.get("vsfJp").toString());
				tpProductBqSp.setCommodityProperty(commodityProperty);
				if(tpProductBqSp.getId() == null){
					R r = addSp(detailJO, tpProductBqSp, tpProductBq,false);
					if (r.getCode() == 1){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return R.error(r.getMsg());
					}
				} else {
					//判断商品名称是否重复
					if ( tpProductBqSp.getId() == null){
						count  = new TpProductBqSp().setName(tpProductBqSp.getName()).count();
					}else {
						count  = new TpProductBqSp().where("A.name = '" + tpProductBqSp.getName() + "' AND A.id != " +  tpProductBqSp.getId()).count();
					}
//					if (count != 0){
//						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//						return R.error(tpProductBqSp.getName()+"商品名称已存在,保存失败!");
//					}
					tpProductBqSp1 = new TpProductBqSp().setId(tpProductBqSp.getId()).queryFirst();
					tpProductBqSp1.setName(detailJO.get("name").toString());
					tpProductBqSp1.setPriceService(new BigDecimal(detailJO.get("priceService").toString()));
					tpProductBqSp1.setIsSuperior(detailJO.get("isSuperior").toString());
					tpProductBqSp1.setVsfJp(detailJO.get("vsfJp").toString());
					tpProductBqSp1.setCommodityProperty(commodityProperty);
					if (commodityProperty.equals("精品")){
						if (!tpProductBqSp1.getCode().equals(tpProductBqSp.getCode())){
							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
							return R.error("不允许更改已经保存过的商品编码!");
						}
					}
					tpProductBqSpMapper.update(tpProductBqSp1);
				}
			} catch (Exception e) {
				return R.error("修改商品列表失败!");
			}
		}
		logger.info("商品备案修改传参："+params);
		return R.ok(AddDto.gotoEdit("/web/business/tpProductBq/toEdit?bid=" + tpProductBq.getBid()+"&commodityProperty=" +commodityProperty));
	}


	/**
	 * 删除
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R del(List<String> idList) {
		logger.info("商品信息传参："+idList);
		Long id = 0L;
		try {
			for(int i=0;i<idList.size();i++) {
				id = Long.parseLong(idList.get(i));
				TpProductBqSp tpProductBqSp = new TpProductBqSp().setId(id).queryFirst();
				if (tpProductBqSp == null) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("商品信息不存在!");
				}
				TpProductBq tpProductBq = new TpProductBq().setId(tpProductBqSp.getPid()).queryFirst();
				if (tpProductBq == null) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("商品备案申请不存在!");
				}

				//判断是否实在制单中
				Integer flowState = yspTaskService.flowState(tpProductBq.getBid());

				if (flowState != 0) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("商品备案申请单不是制单中,不允许保存!");
				}
				//判断是否是最后一条
				if (new TpProductBqSp().setPid(tpProductBq.getId()).count() <= 1) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("删除失败,商品列表至少需要一条保存后的信息!");
				}
				tpProductBqSpMapper.deleteTrue(id);
				List<TpProductBqSpZj> tpProductBqSpZjList = new TpProductBqSpZj().setPid(id).queryList();
				for (TpProductBqSpZj tpProductBqSpZj : tpProductBqSpZjList) {
					tpProductBqSpZjMapper.deleteTrue(tpProductBqSpZj.getId());
				}
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("删除失败!");
		}
		return R.ok("删除成功!");
	}

	/**
	 * 删除
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R delete(Long id) {
		logger.info("商品信息传参："+id);
		try {
			TpProductBq tpProductBq = new TpProductBq().setId(id).queryFirst();
			if (tpProductBq == null){
				return R.error("删除失败,商品备案申请不存在!");
			}

			//判断是否实在制单中
			Integer flowState = yspTaskService.flowState(tpProductBq.getBid());

			if (flowState != 0){
				return R.error("商品备案申请单不是制单中,不允许删除!");
			}
			tpProductBqMapper.deleteTrue(id);
			List<TpProductBqSp> tpProductBqSpList = new TpProductBqSp().setPid(id).queryList();
			for (TpProductBqSp tpProductBqSp : tpProductBqSpList){
				tpProductBqSpMapper.deleteTrue(tpProductBqSp.getId());

				List<TpProductBqSpZj> tpProductBqSpZjList = new TpProductBqSpZj().setPid(tpProductBqSp.getId()).queryList();
				for (TpProductBqSpZj tpProductBqSpZj : tpProductBqSpZjList){
					tpProductBqSpZjMapper.deleteTrue(tpProductBqSpZj.getId());
				}
				// 清除旧的商品材质
				businessMapper.deleteTrueTpProductMaterial(tpProductBqSp.getCode(), TpProductMaterialEnum.Type.TP_ProductBqSp.value);
			}

			yspTaskService.flowDelete(tpProductBq.getBid(),tpProductBq.getCreateChangeId());
		} catch (Exception e) {
			return R.error("删除失败!");
		}
		return R.ok("删除成功!");
	}


	/**
	 * 参数验证
	 */
	@Override
	public String checkParams(Map<String, Object> params,Long menuId) throws Exception {
		Predicate<Object> isNotNull = item-> item!=null && !"".equals(item.toString().trim());//是否为空，返回：非空true，空false
		String backMsg = "";
		if(params==null){
			return "参数为空！";
		}
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		if(listField!=null && listField.size()>0){
			for(YsCol item:listField){
				if(!isNotNull.test(params.get(item.getCode()))){
					backMsg = item.getName()+"为空！";
				}
			}
		}
		if(!"1".equals(params.get("boutiqueIsEffect").toString()) && !"0".equals(params.get("boutiqueIsEffect").toString())){
			return "未知的逸思精品生效类型！";
		}
		return backMsg;
	}


	/**
	 * 获取商品编码
	 */
	private String getBm(Long menuId,String preCode) throws Exception {

		YsMenuNo entity = new YsMenuNo().setMenuId(menuId).queryFirst();
		if (entity == null) {
			throw new Exception("尚未设置单号格式");
		} else {

			String today = DateUtil.getYYYY_MM_DD(new Date());

			String connectCode = entity.getConnectCode();
			String middleCode = today.replace("-", "").substring(2);
			Integer currentNo = entity.getCurrentNo();
			if (entity.getCurrentDay().equals(today)) {

				// 当前日期是当天的，则序号+1
				entity.setCurrentNo(currentNo + 1);
				ysMenuNoMapper.update(entity);
				String currentNoNew = String.format("%04d",currentNo);
				return preCode + connectCode + middleCode + connectCode + currentNoNew;
			} else {

				// 当前日期不是当天的，则序号回归，日期回归当天
				currentNo = entity.getStartNo();
				entity.setCurrentNo(currentNo + 1)
						.setCurrentDay(today);
				ysMenuNoMapper.update(entity);
				String currentNoNew = String.format("%04d",currentNo);
				return preCode + connectCode + middleCode + connectCode + currentNoNew;
			}
		}
	}


	@Override
	@Transactional(propagation= Propagation.REQUIRES_NEW)
	public R flowPass(Long id, String loginUserId) throws Exception {

		TpProductBq entity = new TpProductBq().setId(id).queryFirst();
		if (entity == null){
			return R.error("流转失败,商品备案申请不存在!");
		}
		List<TpProductBqSp> tpProductBqSpList = new TpProductBqSp().setPid(entity.getId()).queryList();
		if(entity.getIsCheckByPass()==1){
			for (TpProductBqSp tpProductBqSp : tpProductBqSpList){
				Map<String, Object> infoMap = BeanUtil.beanToMap(tpProductBqSp);
				//验证导入字段
				String backMsg = "";
				//获取pc字段数据
				List<YsCol> listField = new YsCol()
						.where("A.MenuId = "+MENU_ID)
						.setOrderby("A.SortNo ASC")
						.queryList();
				//验证必填字段的非空；其他字段的长度限制、类型
				backMsg = checkUtil.checkTableColLengthAndDataType(
						"TP_ProductBqSp",
						listField,
						infoMap,
						ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1
								&& !"nameEn".equals(ysColItem.getCode())&& !"nameCn".equals(ysColItem.getCode())
								&& !"usageCn".equals(ysColItem.getCode())&& !"materialCn".equals(ysColItem.getCode())
								&& !"usageEn".equals(ysColItem.getCode())&& !"materialEn".equals(ysColItem.getCode())
								&& !"nameUnit".equals(ysColItem.getCode())
				);
				if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
					return R.error(backMsg);
				}
			}
		}



		if (tpProductBqSpList.size() == 0) {
			return R.error("该商品备案申请单不存在商品信息,请核实后再操作!");
		}
		String bid = entity.getBid();
		try {
			Flow f = yspTaskService.flowPass(bid, loginUserId);
			if (f.getCode() == Flow.Code.FAILED.value) {
				return R.error(f.getMsg());
			} else {
				if (f.getState() == Flow.State.FINISH.value) {
					R r = flowFinish(entity, tpProductBqSpList);
					if (r.getCode() == 1){
						return R.error(r.getMsg());
					}
				}
				return R.ok();
			}
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R flowRefuse(Long id, String reason, String loginUserId) throws Exception {
		try {
			TpProductBq entity = new TpProductBq().setId(id).queryFirst();
			if (entity == null){
				return R.error("驳回失败,商品备案申请不存在!");
			}
			String bid = entity.getBid();
			R r = yspTaskService.flowRefuse(bid, reason, loginUserId);
			if (r.getCode() == 1){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error(r.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("服务器正在开小差，请联系客服");
		}
		return R.ok();
	}


	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R flowInit(Long id, String reason, String loginUserId) throws Exception {
		try {
			TpProductBq entity = new TpProductBq().setId(id).queryFirst();
			if (entity == null){
				return R.error("驳回失败,商品备案申请不存在!");
			}
			String bid = entity.getBid();
			R r = yspTaskService.flowInit(bid, reason, loginUserId);
			if (r.getCode() == 1){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error(r.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("服务器正在开小差，请联系客服");
		}
		return R.ok();
	}



	/**
	 * 新增验证参数
	 */
	public R yzcs(TpProductBqSp tpProductBqSp){
		//验证
		if (tpProductBqSp.getName().length() == 0){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("商品名称为空,保存失败!");
		}else if (tpProductBqSp.getName().length() > 100){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("商品名称长度不允许超过100个字符,保存失败!");
		}
		return R.ok();
	}

	@Transactional(propagation= Propagation.REQUIRES_NEW)
	public R flowFinish(TpProductBq entity,List<TpProductBqSp> tpProductBqSpList) throws Exception {
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		tpProductBqMapper.update(entity);

		Date date = new Date();

		//查询产品运营公司
		ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply()
				.addLeftJoin("TS_AccountBandDept t2 on t2.VgsBm = A.VgsBm")
				.where("t2.AccountId = 'CPKF'")
				.queryFirst();
		if (thrOperateCompanyApply == null){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("产品运营公司不存在,核实后再操作!");
		}
		TcgDistribution tcgDistribution1;
		TcgDistributionSon tcgDistributionSon;
		TcgDistributionSon tcgDistributionSonNew;
		List<TcgDistribution> tcgDistributionList;
		List<TpProductActiveComponent> collect;
		BigDecimal priceServiceTol = BigDecimal.ZERO;

		for (TpProductBqSp tpProductBqSp :tpProductBqSpList){
			//新增商品信息
			TpProductBasis tpProductBasis = new TpProductBasis();
			BeanUtils.copyProperties(tpProductBqSp,tpProductBasis);
			tpProductBasis.setCreateTime(date);
			tpProductBasis.setUpdateTime(date);
			tpProductBasis.setVgsBm(entity.getVgsBm());
			tpProductBasis.setIsUsable("启用");
			tpProductBasis.setCreateChangeId(entity.getCreateChangeId());
			if (new TpProductBasis().setCode(tpProductBasis.getCode()).count() > 0) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error("该"+ tpProductBasis.getCode() +"商品编码已存在,核实后再操作!");
			}
			tpProductBasisMapper.insert(tpProductBasis);


			//新增Listing
			TpProductActive tpProductActive = new TpProductActive();
			BeanUtils.copyProperties(tpProductBqSp,tpProductActive);
			tpProductActive.setCreateTime(date);
			tpProductActive.setUpdateTime(date);
			tpProductActive.setVgsBm(entity.getVgsBm());
			tpProductActive.setIsUsable("1");
			tpProductActive.setSUser(entity.getCreateChangeId());
			tpProductActiveMapper.insert(tpProductActive);

			//新增商品和Listing子件
			List<TpProductBqSpZj> tpProductBqSpZjList = new TpProductBqSpZj().setPid(tpProductBqSp.getId()).queryList();
			List<TpProductActiveComponent> tpProductActiveComponents = new ArrayList<>();
			for (TpProductBqSpZj tpProductBqSpZj : tpProductBqSpZjList){
				TpProductBasisComponent tpProductBasisComponent = new TpProductBasisComponent();
				BeanUtils.copyProperties(tpProductBqSpZj,tpProductBasisComponent);
				tpProductBasisComponent.setPcode(tpProductBasis.getCode());
				tpProductBasisComponent.setCreateTime(date);
				tpProductBasisComponent.setUpdateTime(date);
				tpProductBasisComponentMapper.insert(tpProductBasisComponent);

				TpProductActiveComponent tpProductActiveComponent = new TpProductActiveComponent();
				BeanUtils.copyProperties(tpProductBqSpZj,tpProductActiveComponent);
				tpProductActiveComponent.setPcode(tpProductActive.getCode());
				tpProductActiveComponent.setCreateTime(date);
				tpProductActiveComponent.setUpdateTime(date);
				tpProductActiveComponentMapper.insert(tpProductActiveComponent);

				tpProductActiveComponents.add(tpProductActiveComponent);
			}


			//新增商品材质代码
			List<TpProductMaterial> tpProductMaterialList = new TpProductMaterial().setType(TpProductMaterialEnum.Type.TP_ProductBqSp.value).where("A.ProductCode = '" + tpProductBqSp.getCode() + "'").queryList();
			for (int j = 0; j < tpProductMaterialList.size(); j++) {
				Integer type = TpProductMaterialEnum.Type.TP_ProductBasis.value;
				String productCode = tpProductBqSp.getCode();
				Long materialId = tpProductMaterialList.get(j).getMaterialId();
				String materialNameCn = tpProductMaterialList.get(j).getMaterialNameCn();
				String materialNameEn = tpProductMaterialList.get(j).getMaterialNameEn();
				TpProductMaterial tpProductMaterial = TpProductMaterial.tpProductMaterial(type, productCode, materialId, materialNameCn, materialNameEn, 1);
				tpProductMaterialMapper.insert(tpProductMaterial);

				type = TpProductMaterialEnum.Type.TP_ProductActive.value;
				tpProductMaterial = TpProductMaterial.tpProductMaterial(type, productCode, materialId, materialNameCn, materialNameEn, 1);
				tpProductMaterialMapper.insert(tpProductMaterial);
			}

			//新增组装方案维护
			TccAssemblyMaintain tccAssemblyMaintain = new TccAssemblyMaintain();
			tccAssemblyMaintain.setGuid(RandomUtil.getGUID());
			tccAssemblyMaintain.setName("ZZFA001");
			tccAssemblyMaintain.setWay("人工");
			tccAssemblyMaintain.setProductName(tpProductActive.getName());
			tccAssemblyMaintain.setProductID(tpProductActive.getCode());
			tccAssemblyMaintain.setLength(new BigDecimal("0.1"));
			tccAssemblyMaintain.setWidth(new BigDecimal("0.1"));
			tccAssemblyMaintain.setWidth(new BigDecimal("0.1"));
			tccAssemblyMaintain.setWeight(new BigDecimal("0.1"));
			tccAssemblyMaintain.setCreateUser(entity.getCreateChangeId());
			tccAssemblyMaintain.setUpdateUser(entity.getCreateChangeId());
			tccAssemblyMaintain.setProductLength(BigDecimal.ZERO);
			tccAssemblyMaintain.setProductWeight(BigDecimal.ZERO);
			tccAssemblyMaintain.setProductWidth(BigDecimal.ZERO);
			tccAssemblyMaintain.setProductHeight(BigDecimal.ZERO);
			tccAssemblyMaintain.setStatus(1);
			tccAssemblyMaintainMapper.insert(tccAssemblyMaintain);

			if (tpProductBqSp.getPriceService().compareTo(BigDecimal.ZERO) > 0){
				//划出流水
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompany(
						entity.getVgsBm(),thrOperateCompanyApply.getVgsbm(), TransactionTypeEnum.BusinessType.TP_ProductBqSp.name,tpProductBqSp.getPriceService().negate(),
						date,date,"产品服务费，商品备案申请单:" + entity.getBid() +"，商品编码:" + tpProductBqSp.getCode(),
						entity.getBid(),null);

				//划入流水
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompany(
						thrOperateCompanyApply.getVgsbm(),entity.getVgsBm(),TransactionTypeEnum.BusinessType.TP_ProductBqSp.name,tpProductBqSp.getPriceService(),
						date,date,"产品服务费，商品备案申请单:" + entity.getBid() +"，商品编码:" + tpProductBqSp.getCode(),
						entity.getBid(),null);
			}


			//判断是否是精品新增1.0|1.5精品库信息
			if (tpProductBqSp.getCommodityProperty().equals(TpProductBqEnum.CommodityProperty.JP.name)){
				//新增1.5精品库数据
				TpBoutique tpBoutique = new TpBoutique();
				tpBoutique.setCode(tpProductBqSp.getCode());
				tpBoutique.setName(tpProductBqSp.getName());
				tpBoutique.setCodeMerge(tpProductBqSp.getCodeMerge());
				tpBoutique.setBoutiqueIsEffect(0);
				tpBoutique.setStatus(1);
				tpBoutique.setAuthType(0);
				if(tpProductActive!=null){
					if(tpProductActive.getImg()!=null && !"".equals(tpProductActive.getImg())){
						tpBoutique.setCoverImg(tpProductActive.getImg());
					}
				}
				tpBoutiqueMapper.insert(tpBoutique);

				//新增1.5精品库详情
				TpBoutiqueSiteDetail tpBoutiqueSiteDetail = new TpBoutiqueSiteDetail();
				tpBoutiqueSiteDetail.setBoutiqueId(tpBoutique.getId());
				//TpAmazonRegionItem tpAmazonRegionItem = new TpAmazonRegionItem().setCountryName("英国").where("A.Status!=0").queryFirst();
				Map<String,Object> tbSiteList = new TbSite()
						.addLeftJoin("TP_AmazonRegion B ON B.Code = A.RegionCode")
						.addField("B.Name regionName")
						.addLeftJoin("TB_Platform B1 ON B1.Code = B.PlatformCode")
						.addField("B1.Code platformCode")
						.addLeftJoin("TB_Country C ON C.Id = A.CountryId")
						.addField("C.Name countryName")
						.where("C.Name = '英国' AND A.Status!=0 ")
						.queryFirstMap();
				if(tbSiteList!=null && tbSiteList.get("id")!=null) {
					tpBoutiqueSiteDetail.setSiteId(Long.parseLong(tbSiteList.get("id").toString()));//区域站点id
					tpBoutiqueSiteDetail.setStatus(1);
				}
				if(tpBoutique.getCoverImg()!=null && !"".equals(tpBoutique.getCoverImg())){
					tpBoutiqueSiteDetail.setMainPic1(tpBoutique.getCoverImg());
				}
				tpBoutiqueSiteDetail.setCommodityLmId(tpProductBqSp.getCommodityLmId());
				tpBoutiqueSiteDetail.setSizeLength(tpProductBqSp.getSizeLength());
				tpBoutiqueSiteDetail.setSizeWidth(tpProductBqSp.getSizeWidth());
				tpBoutiqueSiteDetail.setSizeHeight(tpProductBqSp.getSizeHeight());
				tpBoutiqueSiteDetail.setSizeWeight(tpProductBqSp.getSizeWeight());
				tpBoutiqueSiteDetail.setPriceJp(tpProductBqSp.getPriceJp());
				tpBoutiqueSiteDetail.setAsinJp(tpProductBqSp.getAsinJp());
				tpBoutiqueSiteDetailMapper.insert(tpBoutiqueSiteDetail);

			}else if (tpProductBqSp.getCommodityProperty().equals(TpProductBqEnum.CommodityProperty.YP.name)){
//				api1688Service.get1688Ph(tpProductActiveComponents,tpProductActive);
				//根据合并商品编码查询1688铺货
				tcgDistributionList = new TcgDistribution().setPcode(tpProductBqSp.getCodeMerge()).where("A.scode IS NOT NULL").queryList();
				for (TcgDistribution tcgDistribution : tcgDistributionList){
					tcgDistribution1 = new TcgDistribution();
					BeanUtils.copyProperties(tcgDistribution,tcgDistribution1);
					tcgDistribution1.setPcode(tpProductBqSp.getCode());
					tcgDistribution1.setPname(tpProductBqSp.getName());
					//拆分获取子件后缀 得到新商品的子件
					String[] scodeListNew = tcgDistribution.getScode().split(tcgDistribution.getPcode());
					if (scodeListNew.length == 2){
						collect = tpProductActiveComponents.stream().filter(item -> item.getCode().contains(scodeListNew[1])).collect(Collectors.toList());
						if (collect.size() != 0){
							tcgDistribution1.setScode(collect.get(0).getCode());
							tcgDistribution1.setSname(collect.get(0).getName());
						}
					}
					tcgDistributionMapper.insert(tcgDistribution1);

//					//子件信息(1.5 采购项目上线 该代码伤处) 20241210 切换到1.5删除该功能
//					tcgDistributionSon = new TcgDistributionSon().setPid(String.valueOf(tcgDistribution.getId())).queryFirst();
//					if (tcgDistributionSon != null){
//						tcgDistributionSonNew = new TcgDistributionSon();
//						BeanUtils.copyProperties(tcgDistributionSon,tcgDistributionSonNew);
//						//拆分获取子件后缀 得到新商品的子件
//						String[] scodeList = tcgDistributionSon.getScode().split(tcgDistribution.getPcode());
//						if (scodeList.length == 2){
//							collect = tpProductActiveComponents.stream().filter(item -> item.getCode().contains(scodeList[1])).collect(Collectors.toList());
//							if (collect.size() != 0){
//								tcgDistributionSonNew.setScode(collect.get(0).getCode());
//							}
//						}
//						tcgDistributionSonNew.setPid(String.valueOf(tcgDistribution1.getId()));
//						tcgDistributionSonMapper.insert(tcgDistributionSonNew);
//					}
				}
			}
		}


		return R.ok();
	}

	private R  addSp(JSONObject detailJO,TpProductBqSp tpProductBqSp,TpProductBq tpProductBq,boolean isYpImport){
		TpProductBasis tpProductBasis = null;
		Integer count = 0;
		int num = 0;
		String code = "";
		try {
			tpProductBqSp.setIsEdit(0);
			String commodityProperty = detailJO.get("commodityProperty").toString();
			String preCode = "M";
			tpProductBqSp.setSpid(0L);
			if (commodityProperty.equals("新品")){
				preCode = "NP";
			} else if (commodityProperty.equals("优品")) {
				preCode = "YP";
				tpProductBqSp.setSpid(Long.valueOf(detailJO.get("spid").toString()));

				tpProductBasis = new TpProductBasis().setId(Long.valueOf(detailJO.get("spid").toString())).queryFirst();
				if (tpProductBasis == null){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("商品库数据不能为空");
				}else {
					BeanUtils.copyProperties(tpProductBasis,tpProductBqSp);
					tpProductBqSp.setIsEdit(1);
				}
				TpCodeNo tpCodeNo = new TpCodeNo().setPreCode(tpProductBasis.getCode()).queryFirst();
				//查询母品商品编码的序号
				if (tpCodeNo == null) {
					//新增
					tpCodeNo = new TpCodeNo();
					tpCodeNo.setCurrentNo(1);
					tpCodeNo.setStartNo(1);
					tpCodeNo.setPreCode(tpProductBasis.getCode());
					num = 1;
					tpCodeNo.setTheirId(tpProductBasis.getId());
					tpCodeNoMapper.insert(tpCodeNo);
				}else {
					//增加
					tpCodeNo.setCurrentNo(tpCodeNo.getCurrentNo() + 1);
					num = tpCodeNo.getCurrentNo();
					tpCodeNoMapper.update(tpCodeNo);
				}

			}else if (commodityProperty.equals("精品")) {
				preCode = "JP";
			}else if (commodityProperty.equals("变体")) {
				preCode = "BT";
			}

			tpProductBqSp.setPid(tpProductBq.getId());

			if (commodityProperty.equals("精品")) {
				if (detailJO.get("code").toString().equals("保存后自动生成")){
					code = getBm(MENU_ID, preCode);
				}else {
					code = detailJO.get("code").toString();

					String regex ="^[\\w\\d]+\\S";
					Pattern pattern = Pattern.compile(regex);
					if (!pattern.matcher(code).find()){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return R.error("商品编码只允许英文字母加数字!");
					}

				}
			}else {
				code = getBm(MENU_ID, preCode);
			}
			if (new TpProductBqSp().setCode(code).count() > 0) {
				return R.error( code +"该商品编码已存在,请核实后再操作!");
			}
			tpProductBqSp.setCode(code);
			tpProductBqSp.setName(detailJO.get("name").toString());
			if (commodityProperty.equals("优品")) {
				tpProductBqSp.setCodeMerge(detailJO.get("codeMerge").toString());
				tpProductBqSp.setName(tpProductBasis.getName() + "-" + String.format("%02d",num));
			}else {
				tpProductBqSp.setCodeMerge(code);
			}
			tpProductBqSp.setPriceService(new BigDecimal(detailJO.get("priceService").toString()));
			tpProductBqSp.setIsSuperior(detailJO.get("isSuperior").toString());
			tpProductBqSp.setVsfJp(detailJO.get("vsfJp").toString());
			tpProductBqSp.setCommodityProperty(commodityProperty);
			R yzcs = yzcs(tpProductBqSp);
			if (yzcs.getCode().equals(1)){
				return yzcs;
			}
			//判断商品名称是否重复
			if(!isYpImport){
//				Integer productBasiscount  = new TpProductBasis().setName(tpProductBqSp.getName()).count();
//				if ( tpProductBqSp.getId() == null){
//					count  = new TpProductBqSp().setName(tpProductBqSp.getName()).count();
//				}else {
//					count  = new TpProductBqSp().where("A.name = '" + tpProductBqSp.getName() + "' AND A.id != " +  tpProductBqSp.getId()).count();
//				}
//				if (count != 0 || productBasiscount != 0){
//					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//					return R.error(tpProductBqSp.getName()+"商品名称已存在,保存失败!");
//				}
			}
			int isAddTtpProductBqSp = tpProductBqSpMapper.insert(tpProductBqSp);
			if(isAddTtpProductBqSp<=0){
				return R.error("新增商品列表失败!");
			}

			//新增子件列表
			if (commodityProperty.equals("优品")){
				List<TpProductBasisComponent> tpProductBasisComponentList = new TpProductBasisComponent().setPcode(tpProductBasis.getCode()).queryList();
				for (TpProductBasisComponent tpProductBasisComponent :tpProductBasisComponentList){
					TpProductBqSpZj tpProductBqSpZj = new TpProductBqSpZj();
					BeanUtils.copyProperties(tpProductBasisComponent,tpProductBqSpZj);
					tpProductBqSpZj.setPcode(tpProductBqSp.getCode());
					tpProductBqSpZj.setPid(tpProductBqSp.getId());

					//查询最大的一条编号
					List<TpProductBqSpZj> tpProductBqSpZjList = new TpProductBqSpZj().setPid(tpProductBqSp.getId()).setOrderby("A.CurrentNo DESC").queryList();
					Integer currentNo = 0;
					if (tpProductBqSpZjList.size() != 0){
						currentNo = tpProductBqSpZjList.get(0).getCurrentNo();
					}
					currentNo++;
					String currentNoNew = String.format("%02d",currentNo);
					//商品编码-01，-02，-03.....
					tpProductBqSpZj.setCode(tpProductBqSp.getCode()+"-"+currentNoNew);
					// 验证订单号
					if (new TpProductBqSpZj().setCode(tpProductBqSpZj.getCode()).count() > 0) {
						return R.error("子件编码已存在");
					}
					tpProductBqSpZj.setCurrentNo(currentNo);
					tpProductBqSpZjMapper.insert(tpProductBqSpZj);
				}

				//新增商品材质代码
				List<TpProductMaterial> tpProductMaterialList = new ArrayList<>();
				if(isYpImport){
					tpProductMaterialList = new TpProductMaterial().setType(TpProductMaterialEnum.Type.TP_ProductBasis.value).where("A.ProductCode = '" + tpProductBasis.getCode() + "'").queryList();
				}else {
					tpProductMaterialList = new TpProductMaterial().setType(TpProductMaterialEnum.Type.TP_ProductBqSp.value).where("A.ProductCode = '" + tpProductBasis.getCode() + "'").queryList();
				}


				for (int j = 0; j < tpProductMaterialList.size(); j++) {
					Integer type = TpProductMaterialEnum.Type.TP_ProductBqSp.value;
					String productCode = tpProductBqSp.getCode();
					Long materialId = tpProductMaterialList.get(j).getMaterialId();
					String materialNameCn = tpProductMaterialList.get(j).getMaterialNameCn();
					String materialNameEn = tpProductMaterialList.get(j).getMaterialNameEn();
					TpProductMaterial tpProductMaterial = TpProductMaterial.tpProductMaterial(type, productCode, materialId, materialNameCn, materialNameEn, 1);
					tpProductMaterialMapper.insert(tpProductMaterial);
				}
			}

		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("保存失败!");
		}
		return R.ok();
	}

	/**
	 * 批量导入精品库信息
	 */
	@Override
	public R importInfo(String rows,Long menuId){
		logger.info("商品备案申请导入的数据：\n"+rows);
		try {
			//获取所有的商品备案商品库信息
			List<TpProductBqSp> tpProductBqSpList= new TpProductBqSp().queryList();
			//查询商品品类
			List<TbBaseinfoSppl> tbBaseinfoSppls = new TbBaseinfoSppl().queryList();
			//查询商品单位
			List<TbBaseinfoDwmc> tbBaseinfoDwmcList = new TbBaseinfoDwmc().queryList();
			//查询商品品名
			List<TbBaseinfoSppm> tbBaseinfoSppmList = new TbBaseinfoSppm().queryList();
			//查询商品用途
			List<TbBaseinfoSpyt> tbBaseinfoSpytList = new TbBaseinfoSpyt().queryList();
			//查询商品材质
			List<TbBaseinfoSpcz> tbBaseinfoSpczList = new TbBaseinfoSpcz().queryList();
			List<TbBaseinfoSppl> tbBaseinfoSpplsNew = null;
			List<TbBaseinfoDwmc> tbBaseinfoDwmcListNew = null;
			List<TbBaseinfoSppm> tbBaseinfoSppmListNew = null;
			List<TbBaseinfoSpyt> tbBaseinfoSpytListNew = null;
			List<TbBaseinfoSpcz> tbBaseinfoSpczListNew = null;
			//获取导入数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int i=0;i<detailList.size();i++){
				JSONObject info = detailList.getJSONObject(i);
				Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
				//验证导入字段
				String backMsg = "";
				//获取pc字段数据
				List<YsCol> listField = new YsCol()
						.where("A.MenuId = "+menuId)
						.setOrderby("A.SortNo ASC")
						.queryList();
				//验证必填字段的非空；其他字段的长度限制、类型
				backMsg = checkUtil.checkTableColLengthAndDataType(
						"TP_ProductBqSp",
						listField,
						infoMap,
						ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1
								&& !"img".equals(ysColItem.getCode())&& !"nameEn".equals(ysColItem.getCode())
								&& !"usageEn".equals(ysColItem.getCode())&& !"materialEn".equals(ysColItem.getCode())
								&& !"codeMerge".equals(ysColItem.getCode())&& !"isSuperior".equals(ysColItem.getCode())
								&& !"vsfJp".equals(ysColItem.getCode())&& !"priceService".equals(ysColItem.getCode())
								&& !"name".equals(ysColItem.getCode())&& !"commodityProperty".equals(ysColItem.getCode())
				);

				if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
					logger.error("第"+(i+1)+"条数据导入有误：\n"+backMsg);
					continue;
				}
				//验证商品编码
				if(info.get("code")==null || "".equals(info.get("code"))){
					logger.error("第"+(i+1)+"条数据商品编码为空");
					continue;
				}
				List<TpProductBqSp> tpProductBqSpList1 = tpProductBqSpList.stream().filter(item->item.getCode().equals(info.get("code").toString())).collect(Collectors.toList());
				if(tpProductBqSpList1.size()<=0){
					logger.error("第"+(i+1)+"条数据商品编码有误");
					continue;
				}
				infoMap.put("id",tpProductBqSpList1.get(0).getId());
				TpProductBqSp updateDate = JSON.parseObject(JSON.toJSONString(infoMap), TpProductBqSp.class);
				//匹配商品品类
				tbBaseinfoSpplsNew = tbBaseinfoSppls.stream().filter(item->item.getCategoryCn().equals(info.get("commodityPl").toString())).collect(Collectors.toList());
				if(tbBaseinfoSpplsNew.size()>0){
					updateDate.setCommodityPlId(tbBaseinfoSpplsNew.get(0).getId());
				}
				//匹配商品单位
				tbBaseinfoDwmcListNew = tbBaseinfoDwmcList.stream().filter(item->item.getNameUnitCn().equals(info.get("nameUnit").toString())).collect(Collectors.toList());
				if(tbBaseinfoDwmcListNew.size()>0){
					updateDate.setNameUnitId(tbBaseinfoDwmcListNew.get(0).getId());
				}
				//匹配商品品名
				tbBaseinfoSppmListNew = tbBaseinfoSppmList.stream().filter(item->item.getNameCn().equals(info.get("nameCn").toString())).collect(Collectors.toList());
				if(tbBaseinfoSppmListNew.size()>0){
					updateDate.setNameId(tbBaseinfoSppmListNew.get(0).getId());
				}
				//匹配商品用途
				tbBaseinfoSpytListNew = tbBaseinfoSpytList.stream().filter(item->item.getUsageCn().equals(info.get("usageCn").toString())).collect(Collectors.toList());
				if(tbBaseinfoSpytListNew.size()>0){
					updateDate.setUsageId(tbBaseinfoSpytListNew.get(0).getId());
				}
				// 清除旧的商品材质
				businessMapper.deleteTrueTpProductMaterial(updateDate.getCode(), TpProductMaterialEnum.Type.TP_ProductBqSp.value);
				//匹配商品材质 (按照逗号拼接)
				String[] materialCnList = info.get("materialCn").toString().split(",");
				for (String materialCn : materialCnList){
					//匹配商品材质
					tbBaseinfoSpczListNew = tbBaseinfoSpczList.stream().filter(item->item.getMaterialCn().equals(materialCn)).collect(Collectors.toList());
					if(tbBaseinfoSpczListNew.size()>0){
						Integer type = TpProductMaterialEnum.Type.TP_ProductBqSp.value;
						String productCode = updateDate.getCode();
						Long materialId = tbBaseinfoSpczListNew.get(0).getId();
						String materialNameCn = tbBaseinfoSpczListNew.get(0).getMaterialCn();
						String materialNameEn = tbBaseinfoSpczListNew.get(0).getMaterialEn();
						TpProductMaterial tpProductMaterial = TpProductMaterial.tpProductMaterial(type, productCode, materialId, materialNameCn, materialNameEn, 1);
						tpProductMaterialMapper.insert(tpProductMaterial);
					}
				}
				//编辑
				tpProductBqSpMapper.update(updateDate);
			}

		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}


		return R.ok("导入成功!");
	}


	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam( String bid) throws Exception{
		Map<String, Object> entity = new TpProductBq().setBid(bid)
				.addLeftJoin("THR_OperateCompanyApply THRO ON  THRO.VGsBm = A.VgsBm")
				.addField("THRO.VGsMc AS vgsMc,THRO.VGsJc AS vgsJc")
				.queryFirstMap();

		YsProcInst ysProcInst = new YsProcInst().setBid(String.valueOf(entity.get("bid"))).queryFirst();
		entity.put("updateTime1", DateUtil.getYYYY_MM_DD_HH_mm_ss(ysProcInst.getUpdateTime()));
		entity.put("vgsJc", entity.get("vgsJc").toString());
		entity.put("vgsMc", entity.get("vgsMc").toString());
		return entity;
	}


	//批量导入-优品
	@Override
	//@Transactional
	public R importInfoYp(String rows,Long menuId)throws Exception{

		String loginUserId = ShiroUtils.getUserId();
		TpProductBq tpProductBq = null;
		String bid = "";
		if(redisUtil.hGet("importInfoYp",loginUserId)!= null && !redisUtil.hGet("importInfoYp",loginUserId).equals("")){
			bid = redisUtil.hGet("importInfoYp",loginUserId).toString();
			tpProductBq = new TpProductBq().setBid(bid).queryFirst();
		}

		//获取导入数据
		JSONArray detailList = JSON.parseArray(rows);
		for(int i=0;i<detailList.size();i++) {
			JSONObject info = detailList.getJSONObject(i);
			//Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
			//验证商品编码
			if (info.get("code") == null || "".equals(info.get("code"))) {
				logger.error("第" + (i + 1) + "条数据商品编码为空");
				//删除
				if(!"".equals(bid)){
					delete(tpProductBq.getId());
					redisUtil.hPut("importInfoYp",loginUserId,"");
				}
				return R.error("第" + (i + 1) + "条数据商品编码为空");
			}
			//验证商品编码
			if (info.get("vgsBm") == null || "".equals(info.get("vgsBm"))) {
				logger.error("第" + (i + 1) + "条数据公司编码为空");
				//删除
				if(!"".equals(bid)){
					delete(tpProductBq.getId());
					redisUtil.hPut("importInfoYp",loginUserId,"");
				}
				return R.error("第" + (i + 1) + "条数据公司编码为空");
			}
			TpProductBasis tpProductBasis = new TpProductBasis()
					.setCode(info.getString("code").trim())
					.queryFirst();
			if(tpProductBasis==null || tpProductBasis.getId()==null){
				logger.error("商品编码："+info.getString("code")+"在商品库中不存在");
				//删除
				if(!"".equals(bid)){
					delete(tpProductBq.getId());
					redisUtil.hPut("importInfoYp",loginUserId,"");
				}
				return R.error("商品编码："+info.getString("code")+"在商品库中不存在");
			}


		}



		if("".equals(bid)){
			bid = commonApiService.getCommonNextBid(menuId);

			redisUtil.hPut("importInfoYp",loginUserId,bid);

			// 验证订单号
			if (new TpProductBq().setBid(bid).count() > 0) {
				return R.error("该商品备案申请单号已存在");
			}
			TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();

			tpProductBq = new TpProductBq();
			tpProductBq.setBid(bid);
			tpProductBq.setVgsBm(detailList.getJSONObject(0).get("vgsBm").toString().trim());
			tpProductBq.setCreateChangeId(String.valueOf(tsUserChange.getId()));
			tpProductBq.setEffectStock(FlowEnum.EffectStock.NOT_EFFECT.value);
			tpProductBq.setStatus(0);
			tpProductBq.setIsCheckByPass(0);//流程审批时，是否进行验证（0否1是）
			//新增母表信息
			tpProductBqMapper.insert(tpProductBq);

			//新增系统审批流
			YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
			if (ysMenu.getFlowModelId().longValue() != 0L) {
				YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
				String codeModel = yspModel.getCode();
				String createUserId = ShiroUtils.getUserId();
				yspTaskService.init(codeModel, bid, createUserId);
			}
		}


		List<Map<String,Object>> addlist = new ArrayList<>();
		for(int i=0;i<detailList.size();i++) {
			JSONObject info = detailList.getJSONObject(i);

			TpProductBasis tpProductBasis = new TpProductBasis()
					.setCode(info.getString("code").trim())
					.queryFirst();

			if(tpProductBasis!=null){
				Map<String,Object> itemBySub = new HashMap<>();

				itemBySub.put("code","保存后自动生成");
				itemBySub.put("name","保存后自动生成");
				itemBySub.put("priceService","0");
				itemBySub.put("codeMerge",tpProductBasis.getCodeMerge()!=null ?tpProductBasis.getCodeMerge():"");
				itemBySub.put("isSuperior","是");
				itemBySub.put("vsfJp",tpProductBasis.getVsfJp());
				itemBySub.put("spid",tpProductBasis.getId());
				itemBySub.put("commodityProperty","优品");
				addlist.add(itemBySub);
			}
		}

		JSONArray detailJA= JSONArray.parseArray(JSON.toJSONString(addlist));

		// 添加新增商品明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			TpProductBqSp tpProductBqSp = JSON.parseObject(JSON.toJSONString(detailJO), TpProductBqSp.class);
			tpProductBqSp.setPid(tpProductBq.getId());
			//查询商品编码
			try {
				R r = addSp(detailJO, tpProductBqSp, tpProductBq,true);
				logger.info("新增商品明细返回："+r);
				if (r.getCode() == 1){
					delete(tpProductBq.getId());
					redisUtil.hPut("importInfoYp",loginUserId,"");
					return R.error(r.getMsg());
				}
			} catch (Exception e) {
				delete(tpProductBq.getId());
				redisUtil.hPut("importInfoYp",loginUserId,"");
				return R.error("新增商品列表失败!");
			}
		}
		return R.ok();



	}


}
